import React from 'react';
import {
    Row,
    Col,
    Table,
    Icon,
    InputNumber,
    Button,
    Modal,
    notification,
    Form,
    Tooltip,
    Switch,
    Popconfirm,
} from 'antd';
import axios from 'axios';
import intercept from '../../../utils/intercept';
import { config } from 'utils';
import { Input } from 'antd';
import '../less/common.less';
import '../less/CustomLine.less';
//import { Map, Marker, NavigationControl, InfoWindow } from 'react-bmap';
import { MyBMap } from './MyBMap'
const Search = Input.Search;
const FormItem = Form.Item;

class CustomTakePoint extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            loading: false,
            pagination: {
                current: 1,
                pagesize: 10
            },
            onChange: this.onChange,
            buslineVisible: false,
            isDisplay: 'none',
            isDisplayFixSeatNum: 'block',
            isEnable: false,
            isUpPoint: false,
            formTitle: '编辑线路信息',
            sorterInfo: null,
            busLineId: 0,
        }
    };

    getTakePoint = (params = {}) => {
        this.setState({
            busLineId: this.props.location.query.busLineId,
        });
        const token = sessionStorage.getItem("token");
        axios
            .get(`${config.api}CustomLine/CustomTakePoint?Page=${params.page}&&PageSize=${this.state.pagination.pageSize}&&BusLineId=${this.props.location.query.busLineId}`, {
                headers: {
                    Authorization: 'Bearer ' + token
                }
            })
            .then((data) => {
                const pagination = {
                    ...this.state.pagination
                };
                pagination.total = data.data.pageList.totalRows;
                pagination.current = params.page;
                this.setState({ loading: false, dataSource: data.data.pageList.collections, pagination });
            })
            .catch(err => {
                intercept;
            })
    }

    openNotification = (title, desc, color) => {
        notification.open({
            message: title,
            description: desc,
            icon: <Icon type="smile-circle" style={{ color: color }} />,
        });
    };

    handleReset = () => {
        this
            .props
            .form
            .resetFields();
    }

    onChange = (pagination, filters, sorter) => {
        this.getTakePoint({
            sortField: sorter.field,
            sortOrder: sorter.order,
            page: pagination.current,
            ...filters
        });
        this.setState({
            sortedInfo: sorter,
        });
    };

    componentDidMount() {
        this.getTakePoint();
    };

    handleCancel = () => {
        this.setState({
            buslineVisible: false
        })
    }

    pointForm = (ev, record) => {
        this.props.form
            .setFieldsValue({
                pointId: record.pointId,
                busLineId: record.busLineId,
                pointName: record.pointName,
                coordinate: record.coordinate,
                //isUpPoint:record.isUpPoint,
                distanceFromStart: record.distanceFromStart,
                //isEnable:record.isEnable,
                area: record.area,
                order: record.order,
            });

        this.setState({
            buslineVisible: true,
            isEnable: record.isEnable,
            isUpPoint: record.isUpPoint,
        })
    }

    addPointForm = () => {
        this.handleReset();
        this.setState({
            buslineVisible: true,
            isEnable: false,
            isWater: false,
            formTitle: '新增乘车点'
        });
        this.props.form
            .setFieldsValue({
                pointId: -1
            });
    }

    editPointEnable = (checked, record) => {
        this.setState({ loading: true });
        const token = sessionStorage.getItem("token");
        let dataSource = this.state.dataSource;
        for (let i = 0; i < dataSource.length; i++) {
            if (dataSource[i].pointId == record.pointId) {
                dataSource[i].isEnable = checked;
            }
        }

        axios
            .post(`${config.api}CustomLine/CustomEditPoint`, { EditType: 3, PointId: record.pointId, BusLineId: record.busLineId }, { headers: { Authorization: 'Bearer ' + token } })
            .then((data) => {
                if (data.data.result) {
                    this.openNotification("状态修改", checked ? "开启成功" : "关闭成功", "#108ee9");
                }
                else {
                    this.openNotification("状态修改", data.data.errorMessage, "red");
                    for (let i = 0; i < dataSource.length; i++) {
                        if (dataSource[i].pointId == record.pointId) {
                            dataSource[i].isEnable = !checked;
                        }
                    }
                }
                this.setState({ loading: false, dataSource });
            }).catch(err => {
                intercept;
            });
    }

    deletePoint = (record) => {
        const token = sessionStorage.getItem("token");
        axios
            .post(`${config.api}CustomLine/CustomEditPoint`, { EditType: 2, PointId: record.pointId, BusLineId: record.busLineId }, {
                headers: {
                    Authorization: 'Bearer ' + token
                }
            })
            .then((data) => {
                if (data.data.result) {
                    this.setState({ buslineVisible: false });
                    this.handleReset();

                    let dataSource = this.state.dataSource;
                    let index=-1;
                    for (let i = 0; i < dataSource.length; i++) {
                        if (dataSource[i].pointId == record.pointId) {
                            index=i;
                        }
                    }
                    dataSource.splice(index,1);
                    this.setState({
                        dataSource,
                    });
                    this.openNotification("删除站点", "删除站点成功", "#108ee9");
                } else {
                    this.openNotification("删除站点", data.data.errorMessage, "red");
                }
                this.setState({ loading: false });
            }).catch(err => {
                intercept;
            })
    }

    editPoint = (e) => {
        e.preventDefault();
        let pointId = this.props.form.getFieldValue('pointId');
        this
            .props
            .form
            .validateFieldsAndScroll((err, values) => {
                if (!err) {
                    this.setState({ loading: true });
                    const token = sessionStorage.getItem("token");
                    let editType = 1;
                    if (pointId < 0) {
                        editType = 0;
                    }
                    let postdata = {
                        editType: editType,
                        pointId: values.pointId,
                        busLineId: this.state.busLineId,
                        pointName: values.pointName,
                        coordinate: values.coordinate,
                        isUpPoint: this.state.isUpPoint,
                        distanceFromStart: values.distanceFromStart,
                        isEnable: this.state.isEnable,
                        area: values.area,
                        order: values.order
                    }
                    axios
                        .post(`${config.api}CustomLine/CustomEditPoint`, postdata, {
                            headers: {
                                Authorization: 'Bearer ' + token
                            }
                        })
                        .then((data) => {
                            if (data.data.result) {
                                //this.openNotification("编辑线路", "修改线路信息成功", "#108ee9");
                                this.setState({ buslineVisible: false });
                                this
                                    .props
                                    .form
                                    .resetFields();

                                let dataSource = this.state.dataSource;
                                let response = dataSource.filter(m => m.pointId == data.data.takePoint.pointId);
                                //新增
                                if (response.length <= 0) {
                                    dataSource.unshift(data.data.takePoint);
                                    this.openNotification("添加站点", "添加站点成功", "#108ee9");
                                }
                                //编辑
                                else {
                                    for (let i = 0; i < dataSource.length; i++) {
                                        if (dataSource[i].pointId == data.data.takePoint.pointId) {
                                            dataSource[i] = data.data.takePoint;
                                        }
                                    }
                                    this.openNotification("编辑站点", "修改站点信息成功", "#108ee9");
                                }
                                this.setState({
                                    dataSource,
                                });
                            } else {
                                this.openNotification("编辑站点", data.data.errorMessage, "red");
                            }
                            this.setState({ loading: false });
                        }).catch(err => {
                            intercept;
                        })
                }
            });

    }

    onSwitchChange = (checked, type) => {
        if (type == 1) {
            this.setState({
                isUpPoint: !checked,
            });
        } else {
            this.setState({
                isEnable: !checked
            });
        }
    }

    render() {
        let sortedInfo = this.state.sortedInfo || {};
        const columns = [
            {
                title: '乘车点名称',
                dataIndex: 'pointName',
                width: 200
            },
            {
                title: '坐标',
                dataIndex: 'coordinate',
                width: 100
            },
            {
                title: '距起点距离（km）',
                dataIndex: 'distanceFromStart',
                width: 150
            },
            {
                title: '序号',
                dataIndex: 'order',
                width: 100,
                sorter: (a, b) => a.order - b.order,
                sortOrder: sortedInfo.columnKey === 'order' && sortedInfo.order,
            },
            {
                title: '类型',
                dataIndex: 'isUpPoint',
                width: 100,
                render: (text, record) => {
                    return (<span style={record.isUpPoint ? { color: '#108ee9' } : { color: 'red' }}>
                        {record.isUpPoint ? "上车点" : "下车点"}
                    </span>)
                }
            },
            {
                title: '是否启用',
                dataIndex: 'isEnable',
                width: 100,
                render: (text, record) => {
                    return (<Switch
                        checkedChildren="开"
                        unCheckedChildren="关"
                        onChange={(checked, values) => {
                            this.editPointEnable(checked, record)
                        }}
                        checked={record.isEnable}
                    />)
                }
            },
            {
                title: '操作',
                key: 'operation',
                width: 150,
                render: (text, record) => {
                    return (
                        <div>
                            <span><Button type="primary" onClick={(ev, data) => { this.pointForm(ev, record) }}>编辑</Button></span>
                            <span style={{ visibility: 'hidden' }}>藏</span>
                            <span>
                                <Popconfirm placement="top" title={"确定要删除该站点吗？"} onConfirm={(data) => this.deletePoint(record)} okText="确定" cancelText="取消">
                                    <Button type="danger" ghost>删除</Button>
                                </Popconfirm>
                            </span>
                        </div>
                    )
                }
            },
        ];

        const { getFieldDecorator } = this.props.form;
        const className = "components-table-demo-nested";
        const formItemLayout = {
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 6
                }
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 14
                }
            }
        };

        return (
            <div>
                <Row gutter={8} style={{
                    //marginTop: '10px'
                }}>
                    <Col span={2}></Col>
                    <Col span={20}>
                        <div
                            style={{
                                margin: 10
                            }}>
                            <Search
                                style={{
                                    width: 600,
                                    visibility: 'hidden'
                                }}
                            />
                            <Button type="primary" style={{ float: 'right' }} onClick={this.addPointForm}>新增</Button>
                        </div>
                        <Table
                            rowKey={record => record.pointId}
                            {...this.state}
                            bordered={true}
                            className={className}
                            columns={columns}
                            style={{ background: 'white' }}
                        />
                    </Col>
                    <Col span={2}></Col>
                </Row>
                <Modal
                    title={this.state.formTitle}
                    width={1000}
                    visible={this.state.buslineVisible}
                    footer={null}
                    onCancel={this.handleCancel}
                    maskClosable={false}
                >
                    <Form onSubmit={(e, type) => this.editPoint(e)} className="ant-advanced-search-form">
                        <Row>
                            <Col span={12}>
                                <FormItem
                                    style={{ display: 'none' }}
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            乘车点ID
                                    <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('pointId', {
                                        rules: [
                                            {
                                                required: false,
                                            }
                                        ]
                                    })(<Input />)}
                                </FormItem>
                                <FormItem
                                    style={{ display: 'none' }}
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            线路ID
                                    <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('busLineId', {
                                        rules: [
                                            {
                                                required: false,
                                            }
                                        ]
                                    })(<Input />)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            乘车点名称
                                    <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('pointName', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入站点名称',
                                            }
                                        ]
                                    })(<Input />)}
                                </FormItem>

                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            区域
                                    <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('area', {
                                        rules: [
                                            {
                                                required: false,
                                            }
                                        ]
                                    })(<Input />)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            类型
                                    <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {(<Switch checkedChildren="上车点"
                                        unCheckedChildren="下车点"
                                        checked={this.state.isUpPoint}
                                        onChange={(checked, type) => {
                                            this.onSwitchChange(this.state.isUpPoint, 1)
                                        }}
                                    />)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            距起点距离(km)
                                    <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('distanceFromStart', {
                                        rules: [
                                            {
                                                required: false,
                                            }
                                        ]
                                    })(<InputNumber />)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            序号
                                    <Tooltip title="由小到大代表先后顺序">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('order', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入站点顺序号（由小到大代表先后顺序）',
                                            }
                                        ]
                                    })(<InputNumber step='0' />)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            是否启用
                                    <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {(<Switch checkedChildren="启用"
                                        unCheckedChildren="禁用"
                                        checked={this.state.isEnable}
                                        onChange={(checked, type) => {
                                            this.onSwitchChange(this.state.isEnable, 2)
                                        }}
                                    />)}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            坐标
                                    <Tooltip title="在地图上选择坐标">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                >
                                    {getFieldDecorator('coordinate', {
                                        rules: [
                                            {
                                                required: false,
                                                message: '请在地图上选择站点坐标',
                                            }
                                        ]
                                    })(<MyBMap></MyBMap>)
                                    }
                                </FormItem>
                            </Col>
                        </Row>

                        <Row>
                            <Col span={24}>
                                <FormItem className="center">
                                    <Button onClick={this.handleReset}>重置</Button>{' '}
                                    <Button type="primary" htmlType="submit">确定</Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
            </div>
        )
    }
}

const CustomLineTakePoint = Form.create()(CustomTakePoint);
export default CustomLineTakePoint
